<!-- 关联经销商 -->
<script setup lang='ts'>
import type { VxeGridProps, VxeTableInstance } from 'vxe-table'

import { Search } from '@element-plus/icons-vue'
import { exportRelativeEnterprise, useGetEnterpriseSuppliers, useGetSupplierApplyStatusOptions } from '@fl/api/supplier'
import { SearchTable } from '@fl/components'
import SubmitBtn from '@fl/components/submit-btn.vue'
import { downloadFileWithUrl, singleFileJsonObj } from '@fl/utils/fn'

import AddOrEdit from './add-or-edit.vue'
import { STATUS_MAP } from './constant'
import Detail from './detail.vue'
import rejectReason from './reject-reason.vue'

const showAddOrEdit = ref<boolean>(false)
const rejectVisible = ref<boolean>(false)
const showDetail = ref<boolean>(false)
const addOrEditId = ref<string>('')
const detailId = ref<string>('')
const id = ref<string>('')

const inputEnterpriseName = ref<string>('')
const searchText = ref<string>('')
const status = ref<string | undefined>(undefined)
const tablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})
const getEnterpriseSuppliersParams = computed(() => ({
    name: searchText.value,
    page: tablePage.currentPage,
    size: tablePage.pageSize,
    status: status.value,
}))

const { data: supplierApplyStatusData, isLoading: isGetSupplierApplyStatusLoading } = useGetSupplierApplyStatusOptions()
const {
    data: enterpriseSuppliersData,
    isLoading: isGetEnterpriseSuppliersLoading,
    total: enterpriseSuppliersTotal,
} = useGetEnterpriseSuppliers(getEnterpriseSuppliersParams)

// #region Table
const tableRef = ref<VxeTableInstance>()
const isTableLoading = computed(() => isGetSupplierApplyStatusLoading.value || isGetEnterpriseSuppliersLoading.value)

const gridOptions = reactive<VxeGridProps>({
    columns: [
        { field: 'supplierName', title: '供应商名称', width: 240 },
        { field: 'catName', title: '授权品类', width: 240 },
        { field: 'brandName', title: '代理品牌', width: 170 },
        { field: 'file', slots: { default: 'file' }, title: '厂家授权函', width: 170 },
        { field: 'createBy', title: '申请人', width: 120 },
        { field: 'provinceCityCounty', slots: { default: 'province_city_county' }, title: '授权地区', width: 200 },
        { field: 'createTime', title: '申请时间', width: 170 },
        { field: 'updateTime', title: '最新确认时间', width: 170 },
        { field: 'status', fixed: 'right', formatter: formatStatus, title: '状态', width: 100 },
        { field: 'operation', fixed: 'right', slots: { default: 'operation' }, title: '操作', width: 300 },
    ],
})

function formatStatus({ cellValue }) {
    return supplierApplyStatusData.value?.find((item: any) => item.value === String(cellValue))!.label
}

watchEffect(() => {
    tablePage.total = enterpriseSuppliersTotal.value
})
// #endregion

// #region UI Listener
function onApplyBtnClick() {
    addOrEditId.value = ''
    showAddOrEdit.value = true
}

function onSearchBtnClick() {
    searchText.value = inputEnterpriseName.value
    tablePage.currentPage = 1
}

async function onCheckDetailBtnClick(row: any) {
    detailId.value = row.id
    showDetail.value = true
}

async function onReapplyBtnClick(row: any) {
    addOrEditId.value = row.id
    showAddOrEdit.value = true
}

function onRejectReasonBtnClick(row: any) {
    id.value = row.id
    rejectVisible.value = true
}

async function onExportBtnClick() {
    try {
        await exportRelativeEnterprise({
            name: searchText.value,
            page: tablePage.currentPage,
            size: tablePage.pageSize,
            status: status.value,
        }, '供应商列表.xls')
        ElMessage.success('导出成功')
    }
    catch (error) {
        ElMessage.error('导出失败')
    }
}

function onStatusChange(_value: any) {
    tablePage.currentPage = 1
}
// #endregion
</script>

<template>
    <el-card class="mb-20"
             shadow="never"
    >
        状态：
        <el-segmented v-model="status"
                      :options="supplierApplyStatusData"
                      @change="onStatusChange"
        >
            <template #default="{ item }">
                <div class="p-2 flex flex-col gap-2 items-center">
                    <div>{{ item.label }}</div>
                </div>
            </template>
        </el-segmented>
    </el-card>

    <el-card shadow="never">
        <SearchTable v-bind="gridOptions"
                     ref="tableRef"
                     v-model:pager="tablePage"
                     :data="enterpriseSuppliersData"
                     :loading="isTableLoading"
        >
            <template #toolbar_buttons>
                <div class="mb-12 flex w-full justify-between">
                    <div>
                        <el-button type="primary"
                                   @click="onApplyBtnClick"
                        >
                            <div class="i-ic:baseline-add size-16" />
                            发起申请
                        </el-button>

                        <el-button type="primary"
                                   @click="onExportBtnClick"
                        >
                            <div class="i-iconamoon:upload size-16" />
                            导出
                        </el-button>
                    </div>

                    <el-input v-model="inputEnterpriseName"
                              class="!w-300"
                              placeholder="请输入企业名称进行搜索"
                    >
                        <template #append>
                            <SubmitBtn :icon="Search"
                                       style="background: #da0004; color:#fff"
                                       class="w-40 !pl-12"
                                       @click="onSearchBtnClick"
                            />
                        </template>
                    </el-input>
                </div>
            </template>

            <template #province_city_county="{ row }">
                {{ `${row.province}${row.city}${row.county}` }}
            </template>

            <template #file="{ row }">
                <span class="text-#409EFF truncate cursor-pointer"
                      @click="downloadFileWithUrl(singleFileJsonObj(row.file).url, singleFileJsonObj(row.file).name)"
                >
                    {{ singleFileJsonObj(row.file).name }}
                </span>
            </template>

            <template #operation="{ row }">
                <el-button text
                           type="primary"
                           class="!p-4"
                           @click="onCheckDetailBtnClick(row)"
                >
                    查看
                </el-button>

                <SubmitBtn v-if="(row.status === STATUS_MAP.REJECTED && row.userRole === 10) || row.status === STATUS_MAP.COOPERATING || (row.status === STATUS_MAP.COOPERATE_TERMINATED && row.userRole === 10)"
                           text
                           type="primary"
                           class="!p-4"
                           @click="onReapplyBtnClick(row)"
                >
                    编辑
                </SubmitBtn>

                <el-button v-if="row.status === STATUS_MAP.REJECTED"
                           text
                           type="primary"
                           class="!p-4"
                           @click="() => onRejectReasonBtnClick(row)"
                >
                    驳回原因
                </el-button>
            </template>
        </SearchTable>
    </el-card>

    <AddOrEdit :key="addOrEditId"
               v-model:id="addOrEditId"
               v-model:visible="showAddOrEdit"
    />

    <Detail :key="detailId"
            v-model:id="detailId"
            v-model:visible="showDetail"
    />

    <rejectReason v-model:id="id"
                  v-model:rejectVisible="rejectVisible"
    />
</template>

<style lang="scss" scoped>
:deep(.el-input-group__append) {
    width: 40px;
    padding: 0;
}
</style>
